<template>
  <div class="resource">
    <div class="res-wrapper">
      <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
        <el-tab-pane label="创建导航" name="first">
          <el-form
            :model="navForm"
            :rules="navRules"
            ref="navForm"
            label-width="80px"
            class="nav-form"
          >
            <el-form-item label="导航名称" prop="label">
              <el-input v-model="navForm.label"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitNavForm('navForm')">立即创建</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="上传资源" name="second">
          <loading v-if="!navData"></loading>
          <nodata v-else-if="!navData.length"></nodata>
          <el-form
            :model="resForm"
            :rules="resRules"
            ref="resForm"
            label-width="140px"
            class="res-from"
            v-else
          >
            <el-form-item label="选择导航栏" prop="navName">
              <el-select v-model="resForm.navName" placeholder="请选择资源归属于的导航栏">
                <el-option
                  v-for="data in navData"
                  :key="data._id"
                  :label="data.label"
                  :value="data.label"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="分类选择" prop="classChild" v-if="getNavDataClass.length">
              <el-radio-group v-model="resForm.classChild">
                <el-radio v-for="data in getNavDataClass" :key="data.id" :label="data"></el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item v-if="resForm.navName" label="新加分类标题">
              <el-input
                v-model="newClassData"
                maxlength="18"
                show-word-limit
                :placeholder="'添加到'+(resForm.navName)+'导航中'"
              ></el-input>
              <el-button @click="addNavClass(newClassData,resForm.navName)">添加</el-button>
            </el-form-item>
            <el-form-item label="资源名称" prop="name">
              <el-input v-model="resForm.name"></el-input>
            </el-form-item>
            <el-form-item prop="desc" label="资源描述">
              <el-input type="textarea" :autosize="{minRows:4}" v-model="resForm.desc"></el-input>
            </el-form-item>
            <el-form-item label="下载所需积分" prop="integral">
              <el-slider v-model="resForm.integral" show-input :max="sliderMaxLength"></el-slider>
            </el-form-item>
            <el-form-item class="upload-wrapper">
              <div>
                <p>
                  <strong>资源封面：</strong>只能上传一张图片，且大小不能超过1M，格式为jpeg/png
                </p>
                <el-upload
                  class="upload"
                  ref="uploadImg"
                  action
                  list-type="picture-card"
                  :limit="limitNum"
                  :http-request="addAttachment"
                  :before-upload="beforeAvatarUpload"
                >
                  <i class="el-icon-plus"></i>
                </el-upload>
              </div>
              <div>
                <p>
                  <strong>资源：</strong>只能上传psd文件或者压缩包（.rar/.zip）,且大小不超过30M
                </p>
                <el-upload
                  class="upload"
                  ref="uploadPackage"
                  action
                  list-type="picture-card"
                  :limit="limitNum"
                  :http-request="addAttachmentPackage"
                  :before-upload="beforeAvatarUploadPackage"
                >
                  <i class="el-icon-plus"></i>
                </el-upload>
              </div>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                :disabled="disabledFlog"
                @click="submitResForm('resForm')"
              >立即上传</el-button>
              <el-button @click="resetResForm('resForm')">重置</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script>
import { mapState, mapActions } from "Vuex";
export default {
  name: "admin-resource",
  watch: {
    "resForm.navName": {
      handler(newVal, oldVal) {
        this.resForm.classChild = "";
      },
      deep: true
    }
  },
  data() {
    return {
      disabledFlog: false,
      activeName: "first",
      navData: "",
      limitNum: 1,
      newClassData: "",
      sliderMaxLength: 5,
      navForm: {
        label: "",
        userName: ""
      },
      navRules: {
        label: [
          { required: true, message: "请输入导航名称", trigger: "blur" },
          { min: 2, max: 18, message: "长度在 2 到 18 个字符", trigger: "blur" }
        ]
      },
      resForm: {
        navName: "",
        name: "",
        desc: "",
        classChild: "",
        integral: 0,
        fileData: {},
        package: {}
      },
      resRules: {
        name: [
          { required: true, message: "请输入资源名称", trigger: "blur" },
          { min: 2, max: 18, message: "长度在 2 到 18 个字符", trigger: "blur" }
        ],
        navName: [
          { required: true, message: "请选择导航位置", trigger: "blur" }
        ],
        desc: [
          { required: true, message: "请输入资源描述", trigger: "blur" },
          {
            min: 2,
            max: 3000,
            message: "长度在 2 到 3000 个字符",
            trigger: "blur"
          }
        ],
        classChild: [
          { required: true, message: "请选择导航下的分类", trigger: "blur" }
        ],
        integral: [
          {
            required: true,
            message: "请选择下载所需积分（建议设定为1个积分）",
            trigger: "blur"
          }
        ]
      }
    };
  },
  computed: {
    getNavDataClass() {
      let navData = this.navData;
      let navName = this.resForm.navName;
      if (navData && navData.length && navName) {
        let data = null;
        for (let i = 0; i < navData.length; i++) {
          if (navData[i].label === navName) {
            data = navData[i].class;
            break;
          }
        }
        return data;
      } else {
        return [];
      }
    },
    ...mapState("user", ["userName"])
  },
  methods: {
    resetResForm(formName) {
      // 清除上传资源的数据集合resForm
      this.resForm.fileData = {};
      this.resForm.package = {};
      this.$refs.uploadImg.clearFiles();
      this.$refs.uploadPackage.clearFiles();
      this.$refs[formName].resetFields();
    },
    addAttachment(file) {
      this.resForm.fileData = file.file;
    },
    addAttachmentPackage(file) {
      this.resForm.package = file.file;
    },
    beforeAvatarUploadPackage(file) {
      let name = file.name.split(".");
      let length = name.length;
      const flog =
        name[length - 1] === "rar" ||
        name[length - 1] === "psd" ||
        name[length - 1] === "zip";

      const isLt1M = file.size / 1024 / 1024 < 30;

      if (!flog) {
        this.$message.error("上传资源只能是 zip/rar/psd 格式!");
      }
      if (!isLt1M) {
        this.$message.error("上传资源大小不能超过 30MB!");
      }
      return flog && isLt1M;
    },
    beforeAvatarUpload(file) {
      const flog = file.type === "image/png" || file.type === "image/jpeg";
      const isLt1M = file.size / 1024 / 1024 < 1;

      if (!flog) {
        this.$message.error("上传头像图片只能是 JPG/PNG 格式!");
      }
      if (!isLt1M) {
        this.$message.error("上传头像图片大小不能超过 1MB!");
      }
      return flog && isLt1M;
    },
    submitResForm(formName) {
      // 上传资源的方法
      this.$refs[formName].validate(valid => {
        if (valid) {
          let resForm = this.resForm;
          if (
            resForm.classChild &&
            resForm.package.name &&
            resForm.fileData.name
          ) {
            this.disabledFlog = true;
            this.$notify.info({
              title: "消息",
              message: "请稍后，正在上传数据。"
            });

            let collections = new FormData();
            collections.append("navName", resForm.navName);
            collections.append("name", resForm.name);
            collections.append("desc", resForm.desc);
            collections.append("classChild", resForm.classChild);
            collections.append("integral", resForm.integral);
            collections.append("image", resForm.fileData);
            collections.append("package", resForm.package);
            collections.append("userName", this.userName);
            this.setResourceData(collections)
              .then(res => {
                if (res.data.ok === 1) {
                  this.disabledFlog = false;
                  this.$notify({
                    title: "消息",
                    type: "success",
                    message: "数据上传成功。"
                  });
                  this.resetResForm("resForm");
                }
              })
              .catch(err => {
                console.log(err);
              });
          } else {
            alert("图片或者资源未上传，请上传后提交");
          }
        }
      });
    },
    handleClick(data) {
      if (data.index === "1") {
        this.getNavData()
          .then(res => {
            if (res.data.ok === 1) {
              this.navData = res.data.data;
            }
          })
          .catch(err => {
            console.log(err);
          });
      }
    },
    addNavClass(data, navForm) {
      // 添加分类到导航下的class中
      if (data) {
        this.addNavClassData({
          class: data,
          label: navForm
        })
          .then(res => {
            if (res.data.ok === 1) {
              this.getNavData()
                .then(res => {
                  if (res.data.ok === 1) {
                    this.navData = res.data.data;
                    this.newClassData = "";
                  } else {
                    alert(res.data.data);
                  }
                })
                .catch(err => {
                  console.log(err);
                });
            } else {
              alert(res.data.ok + ":" + res.data.data);
            }
          })
          .catch(err => {
            console.log(err);
          });
      } else {
        alert("请输入分类标题");
      }
    },
    submitNavForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let collections = {
            label: this.navForm.label,
            userName: this.userName
          };
          this.setNavData(collections).then(res => {
            if (res.data.ok === 1) {
              alert("新建导航成功--" + res.data.data.label);
            } else {
              alert(res.data.data);
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    ...mapActions("user", [
      "getNavData",
      "setNavData",
      "addNavClassData",
      "setResourceData"
    ])
  }
};
</script>

<style scoped lang="sass">
@import '@/assets/default.sass'
.resource
  width: 100%
  padding: 20px
  min-height: 700px
  .res-wrapper
    width: 100%
    .el-tabs
      .nav-form
        width: 100%
        padding: 5%
        .el-form-item
          margin: 80px 0    
</style>


<style lang="sass">
@import '@/assets/default.sass'
.res-wrapper
  .upload-wrapper
      .el-form-item__content
        @include flex(center,center)
        >div
          flex: 1
          padding: 0 20px
          p
            line-height: 20px
            height: 40px
</style>